package com.atguigu.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * @Description: 读取消息
     * @param ctx:  下上文对象，含有管道，通道，地址
     * @param msg: 客户端发送的对象
     * @return void
     * @since 2021/3/14 16:05
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server ctx =" + ctx);
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端的消息 = " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址 = " + ctx.channel().remoteAddress());
    }

    /**
     * @Description: 数据读取完毕
     * @param ctx:
     * @return void
     * @since 2021/3/14 16:08
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello ~ 客户端",CharsetUtil.UTF_8));

    }

    /**
     * @Description:  异常处理
     * @param ctx:
     * @param cause:
     * @return void
     * @since 2021/3/14 16:09
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
